<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>共用图例的双饼图联动</title>
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            display: flex;
            flex-direction: column;
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 8px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            padding: 20px;
        }
        .legend-container {
            text-align: center;
            margin-bottom: 20px;
        }
        .charts-wrapper {
            display: flex;
            gap: 20px;
        }
        .chart {
            flex: 1;
            min-width: 0;
        }
        #chart1, #chart2 {
            width: 100%;
            height: 200px;
        }
        .chart-title {
            text-align: center;
            font-size: 16px;
            font-weight: bold;
            margin-top: 10px;
            color: #333;
        }
        .export-btn {
            color: #1890ff;
            margin-left: 10px;
            font-weight: normal;
            cursor: pointer;
        }
        .legend-item {
            display: inline-block;
            margin: 0 15px;
            cursor: pointer;
            padding: 5px 10px;
            border-radius: 4px;
            transition: all 0.3s;
        }
        .legend-item:hover {
            background-color: #f0f0f0;
        }
        .legend-color {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 6px;
            margin-right: 5px;
            vertical-align: middle;
        }
        .legend-item.inactive {
            opacity: 0.5;
            text-decoration: line-through;
        }
        @media (max-width: 768px) {
            .charts-wrapper {
                flex-direction: column;
            }
            /* 为小尺寸屏幕添加特殊样式 */
            .small-chart #chart1, .small-chart #chart2 {
                height: 100px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 切换图表大小的按钮 -->
        <div style="text-align: center; margin-bottom: 15px;">
            <button id="toggleSizeBtn" class="btn btn-primary">切换图表大小</button>
        </div>
        
        <!-- 共用图例容器 -->
        <div class="legend-container" id="sharedLegend"></div>
        
        <div class="charts-wrapper" id="chartsWrapper">
            <div class="chart">
                <div id="chart1"></div>
                <div class="chart-title">
                    数量占比
                    <span class="export-btn" onclick="exportChart(1)">导出</span>
                </div>
            </div>
            <div class="chart">
                <div id="chart2"></div>
                <div class="chart-title">
                    面积占比
                    <span class="export-btn" onclick="exportChart(2)">导出</span>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 初始化图表
        const chart1 = echarts.init(document.getElementById('chart1'));
        const chart2 = echarts.init(document.getElementById('chart2'));
        
        // 颜色配置
        const colorPalette = ['#5470C6', '#91CC75', '#FAC858', '#EE6666'];
        
        // 原始数据
        const rawData = {
            quantity: {"":"0.26%","更新意愿未定":"8.67%","有更新意愿或计划":"13.67%","无更新意愿":"17.61%","其他地块":"59.79%"},
            amount: {"":"3.29%","更新意愿未定":"12.86%","有更新意愿或计划":"45.07%","其他地块":"6.28%","无更新意愿":"32.50%"}
        };

        // 处理数据：转换为数组并过滤空键
        function processData(rawData) {
            return Object.entries(rawData)
                .filter(([name]) => name.trim() !== "")
                .map(([name], index) => ({
                    name,
                    value: parseFloat(rawData[name])
                }));
        }

        // 获取所有类别（排除空键）
        const categories = [...new Set([
            ...Object.keys(rawData.quantity),
            ...Object.keys(rawData.amount)
        ].filter(name => name.trim() !== ""))];

        // 当前选中状态
        let selectedState = {};
        categories.forEach(category => {
            selectedState[category] = true;
        });
        
        // 图表大小状态
        let isSmallSize = false;

        // 创建自定义图例
        function createSharedLegend() {
            const legendContainer = document.getElementById('sharedLegend');
            legendContainer.innerHTML = '';
            
            categories.forEach((category) => {
                const legendItem = document.createElement('div');
                legendItem.className = `legend-item ${selectedState[category] ? '' : 'inactive'}`;
                legendItem.dataset.category = category;
                
                // 图例颜色标记 - 使用与图表一致的颜色映射
                const colorMarker = document.createElement('span');
                colorMarker.className = 'legend-color';
                colorMarker.style.backgroundColor = colorPalette[categories.indexOf(category) % colorPalette.length];
                
                // 图例文本
                const text = document.createTextNode(category);
                
                legendItem.appendChild(colorMarker);
                legendItem.appendChild(text);
                legendContainer.appendChild(legendItem);
                
                // 添加点击事件
                legendItem.addEventListener('click', function() {
                    toggleSeries(category);
                });
            });
        }

        // 切换系列显示状态
        function toggleSeries(category) {
            // 切换选中状态
            selectedState[category] = !selectedState[category];
            
            // 更新两个图表
            updateChartData(chart1, 'quantity');
            updateChartData(chart2, 'amount');
            
            // 更新图例样式
            updateLegendStyle(category);
        }

        // 更新图表数据
        function updateChartData(chart, dataType) {
            const rawChartData = rawData[dataType];
            const filteredData = Object.entries(rawChartData)
                .filter(([name]) => name.trim() !== "" && selectedState[name])
                .map(([name]) => ({
                    name,
                    value: parseFloat(rawChartData[name])
                }));
            
            chart.setOption({
                series: [{
                    data: filteredData
                }]
            });
        }

        // 更新图例样式
        function updateLegendStyle(category) {
            const legendItem = document.querySelector(`.legend-item[data-category="${category}"]`);
            if (legendItem) {
                legendItem.classList.toggle('inactive', !selectedState[category]);
            }
        }

        // 根据图表尺寸获取相应配置
        function getChartOptions(isSmall) {
            // 基础配置
            const baseOptions = {
                color: colorPalette,
                tooltip: {
                    trigger: 'item',
                    formatter: '{b}: {c}%'
                },
                series: [{
                    type: 'pie',
                    avoidLabelOverlap: false,
                    itemStyle: {
                        color: function(params) {
                            return colorPalette[categories.indexOf(params.name) % colorPalette.length];
                        }
                    }
                }]
            };
            
            // 小尺寸配置
            if (isSmall) {
                return {
                    ...baseOptions,
                    animation: false, // 禁用动画
                    series: [{
                        ...baseOptions.series[0],
                        radius: ['30%', '60%'], // 减小饼图尺寸
                        label: { show: false }, // 禁用标签
                        labelLine: { show: false }, // 禁用标签线
                        itemStyle: {
                            ...baseOptions.series[0].itemStyle,
                            borderRadius: 2, // 减小圆角
                            borderWidth: 1 // 减小边框宽度
                        }
                    }]
                };
            }
            
            // 正常尺寸配置
            return {
                ...baseOptions,
                animation: true,
                animationDuration: 1000,
                series: [{
                    ...baseOptions.series[0],
                    radius: ['40%', '70%'],
                    label: {
                        show: true,
                        position: 'outside',
                        formatter: '{b}: {c}%'
                    },
                    labelLine: {
                        show: true
                    },
                    itemStyle: {
                        ...baseOptions.series[0].itemStyle,
                        borderRadius: 10,
                        borderWidth: 2
                    }
                }]
            };
        }

        // 初始化图表配置
        function initCharts() {
            // 获取当前尺寸的配置
            const options = getChartOptions(isSmallSize);
            
            // 图表1配置 - 数量
            chart1.setOption({
                title: {
                    text: '数量占比',
                    left: 'center',
                    textStyle: {
                        fontSize: isSmallSize ? 10 : 14
                    }
                },
                ...options,
                series: [{
                    ...options.series[0],
                    name: '数量',
                    data: processData(rawData.quantity)
                }]
            });

            // 图表2配置 - 金额
            chart2.setOption({
                title: {
                    text: '面积占比',
                    left: 'center',
                    textStyle: {
                        fontSize: isSmallSize ? 10 : 14
                    }
                },
                ...options,
                series: [{
                    ...options.series[0],
                    name: '面积',
                    data: processData(rawData.amount)
                }]
            });
        }

        // 导出函数
        function exportChart(type) {
            const chart = type === 1 ? chart1 : chart2;
            const title = type === 1 ? '数量占比' : '面积占比';
            
            const imgData = chart.getDataURL({
                type: 'png',
                pixelRatio: 2,
                backgroundColor: '#fff'
            });
            
            const link = document.createElement('a');
            link.href = imgData;
            link.download = `${title}.png`;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // 切换图表大小
        function toggleChartSize() {
            isSmallSize = !isSmallSize;
            const chartsWrapper = document.getElementById('chartsWrapper');
            
            if (isSmallSize) {
                chartsWrapper.classList.add('small-chart');
                document.getElementById('toggleSizeBtn').textContent = '切换为正常大小';
            } else {
                chartsWrapper.classList.remove('small-chart');
                document.getElementById('toggleSizeBtn').textContent = '切换为小尺寸';
            }
            
            // 重新初始化图表配置
            initCharts();
            
            // 调整图表尺寸
            setTimeout(() => {
                chart1.resize();
                chart2.resize();
            }, 100);
        }

        // 初始化
        function init() {
            initCharts();
            createSharedLegend();
            
            // 响应式调整
            window.addEventListener('resize', function() {
                chart1.resize();
                chart2.resize();
            });
            
            // 添加切换大小按钮事件
            document.getElementById('toggleSizeBtn').addEventListener('click', toggleChartSize);
        }

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', init);
    </script>
</body>
</html>